package 网络编程.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName StreamUtils.java
 * @Description 将输入流转换成byte[], 即可以把文件的内容读入到byte[]
 * @createTime 2023年05月03日 19:35:00
 */
public class StreamUtils {

    public static byte[] streamToByteArray(InputStream is) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建输出对象
        byte[] b = new byte[1024]; //字节数组
        int len;
        while ((len=is.read(b))!=-1){ //循环读取
            bos.write(b,0,len); //读取到的数据，写入bos
        }
        byte[] array = bos.toByteArray(); //然后将bos 转成字节数组
        bos.close();
        return array;
    }


    /**
     * 功能：将InputStream转换成String
     * */
    public static String streamToString(InputStream is) throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine())!=null){
            builder.append(line+"\r\n");
        }
        return builder.toString();
    }

}
